package org.tps.project.services;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

public abstract class AbstractServiceImpl<T> implements AbstractService<T> {
	@PersistenceContext
	protected EntityManager entityManager;
	protected Class<T> aClass;

	@Override
	public T create(T object) {
		entityManager.persist(object);
		return object;
	}

	@Override
	public void delete(T object) {
		entityManager.remove(object);
	}

	@Override
	public T findById(int id) {
		return entityManager.find(aClass, id);
	}

	@Override
	public void update(T object) {
		entityManager.merge(object);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> findAll() {
		Query query = entityManager.createNativeQuery(
				"select * from " + aClass.getSimpleName() + " o", aClass);
		return (List<T>) query.getResultList();
	}
}